<!doctype html>
<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>
<script src="../assert_selection.js"></script>
<div id="sample"></div>
<script>
function assemble(seleciton, source) {
    let sample = seleciton.document.body;
    let expectedEnd;
    let expectedStart;
    let sampleText = '';
    let offset = 0;
    let textNode = sample.appendChild(document.createTextNode(''));
    let startNode;
    let startOffset;
    let endNode;
    let endOffset;
    for (var i = 0; i < source.length; ++i) {
        let ch = source[i];
        switch (ch) {
        case '^':
            expectedStart = offset;
            startNode = textNode;
            startOffset = textNode.length;
            break;
        case '|':
            expectedEnd = offset;
            endNode = textNode;
            endOffset = textNode.length;
            break;
        case ' ':
            textNode = sample.appendChild(document.createTextNode(''));
            break;
        default:
            ++offset;
            sampleText += ch;
            textNode.textContent += ch;
            break;
        }
    }
    seleciton.collapse(startNode, startOffset);
    seleciton.extend(endNode, endOffset);
    sample.normalize();
}

function test_text_normalize(inputText, expectedText) {
    test(() => {
        assert_equals(expectedText.indexOf(' '), -1,
            'expectedText should not have split marker.');
        assert_selection(
            '',
            selection => assemble(selection, inputText),
            expectedText);
    }, inputText);
}

// Note: ' ' denotes end of Text node.
test_text_normalize('^foo| bar baz', '^foo|barbaz');
test_text_normalize('foo ^bar| baz', 'foo^bar|baz');
test_text_normalize('foo bar ^baz|', 'foobar^baz|');
test_text_normalize('f^oo ba|r baz', 'f^ooba|rbaz');
test_text_normalize('f^oo bar ba|z', 'f^oobarba|z');
test_text_normalize('foo b^ar ba|z', 'foob^arba|z');
test_text_normalize('f^oo  ba|z', 'f^ooba|z');
test_text_normalize('^foo | baz', '^foo|baz');
test_text_normalize('^foo  baz|', '^foobaz|');
test_text_normalize('foo ^ baz|', 'foo^baz|');
test_text_normalize('foo ^bar |', 'foo^bar|');
</script>
